package com.gq.utils;

import java.io.UnsupportedEncodingException;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;

public class Crypto {

	public static final int KEYSPEC_LENGTH = 16;
	public static final String CIPHER_TRANSFORMATION = "AES/CBC/PKCS5Padding";
	public static final String CIPHER_ALGORITHM = "AES";
	public static byte[] iv;
	
	private static SecretKeySpec skeySpec;
	private static IvParameterSpec ivSpec;
	private Cipher cipher;
	
	static {
		iv = new byte[16];
		ivSpec = new IvParameterSpec(iv);
	}
	
	public Crypto(String password) throws Exception {
		cipher = Cipher.getInstance(CIPHER_TRANSFORMATION);
		byte[] key = toBytePwd(password);
		skeySpec = new SecretKeySpec(key, CIPHER_ALGORITHM);
	}
	
	public static String rightPad(String input, int size) {
		String fm = "%-" + size + "s";
		return String.format(fm, input).replace(' ', '\000');
	}
	
	public static byte[] toBytePwd(String input) {
		byte[] enc = null;
		try {
			enc = rightPad(input, KEYSPEC_LENGTH).getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return enc;
	}
	
	public byte[] encrypt(String clearText) throws Exception {
		byte[] encrypted = null;
		cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivSpec);
		encrypted = cipher.doFinal(clearText.getBytes("UTF-8"));
		return encrypted;
	}
	
	public String encryptToBase64(String clearText) throws Exception {
		byte[] enc = encrypt(clearText);
		return Base64.encodeBase64String(enc);
	}
	
	public byte[] decrypt(byte[] enc) throws Exception {
		cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivSpec);
		byte[] result = cipher.doFinal(enc);
		return result;
	}
	
	public String decryptFromBase64(String encryptedText) throws Exception {
		byte[] enc = Base64.decodeBase64(encryptedText);
		return new String(decrypt(enc), "UTF-8");
	}

}
